
#include "CInputSystemSDL.h"

/// Input System Creation For Direct Input
CInputSystemSDL::CInputSystemSDL( ) : IInputSystem( ) {
	m_MouseState = new byte [8];
	//m_KeyboardState = new byte [256];
	memset( m_MouseState, 0, 8 );
	//memset( m_KeyboardState, 0, 256 );
}
/// Input System Creation For Direct Input
CInputSystemSDL::~CInputSystemSDL( ) {
	FREEA(m_MouseState)
	//FREEA(m_KeyboardState)
}

/// Initialize SDL
/**	@return true if initialization is true */
bool CInputSystemSDL::Initialize( ) {
	SDL_WM_GrabInput( SDL_GRAB_ON );
	m_bInitialized = true;
	return true;
}

/// Bind input to a window
/**	@param hwnd - window handle
		@return true if bind is successful */
bool CInputSystemSDL::Bind( handle hwnd ) {
	if( !m_bInitialized )
		return false;
	return true;
}

/// Refresh input data
/**	@param gameTime - time between frames */
void CInputSystemSDL::Update( creal &gameTime ) {
	if( ! m_bInitialized ) return;

	m_lLastMouseX = m_lMouseX;
	m_lLastMouseY = m_lMouseY;

	for( int i = 0; i < 3; i++ ) {
		m_MouseState[i] & 2 ? m_MouseState[i] = 2 : m_MouseState[i] = 0;
		/*if( m_MouseState[i] & 2 )
			m_MouseState[i] = 2;
		else m_MouseState[i] = 0;*/
	}

	SDL_Event m_Event;
	while( SDL_PollEvent( &m_Event ) ) {
      switch( m_Event.type ) {
			case SDL_MOUSEMOTION:
				m_lMouseXRel = m_Event.motion.xrel;
				m_lMouseYRel = m_Event.motion.yrel;
				m_lMouseX    = 0;
				m_lMouseY    = 0;
				break;
			case SDL_MOUSEBUTTONDOWN:
				switch( m_Event.button.button ) {
					case SDL_BUTTON_LEFT:
						m_MouseState[LEFT_BUTTON] = 3;
						break;
					case SDL_BUTTON_RIGHT:
						m_MouseState[RIGHT_BUTTON] = 3;
						break;
					case SDL_BUTTON_MIDDLE:
						m_MouseState[MIDDLE_BUTTON] = 3;
						break;
				}
				break;
			case SDL_MOUSEBUTTONUP:
				switch( m_Event.button.button ) {
					case SDL_BUTTON_LEFT:
						m_MouseState[LEFT_BUTTON] = 1;
						break;
					case SDL_BUTTON_RIGHT:
						m_MouseState[RIGHT_BUTTON] = 1;
						break;
					case SDL_BUTTON_MIDDLE:
						m_MouseState[MIDDLE_BUTTON] = 1;
						break;
				}
				break;
         default:
				break;
		}
	}

	m_KeyboardState = SDL_GetKeyState(NULL);

	IInputSystem::Update( gameTime );
}

/// Directly check if mouse button is down
byte CInputSystemSDL::IsMouseButtonDownDirect( uint button ) {
	return m_MouseState[button];
}

/// Directly check if keyboard button is down
byte CInputSystemSDL::IsKeyboardButtonDownDirect( uint button ) {
	return m_KeyboardState[button];
}
